﻿#include "TrackBallController.h"
#include<iostream>
TrackBallController::TrackBallController()
{
}

TrackBallController::~TrackBallController()
{
}

void TrackBallController::onCursor(double xpos, double ypos)
{
	if (mLeftMouseDown) {
		float DeltaX = (xpos - mCurrentX) * mSensitive;
		float DeltaY = (ypos - mCurrentY) * mSensitive;

		//分别计算pitch和yaw
		pitch(DeltaY);
		yaw(DeltaX);
		std::cout << DeltaY << std::endl;
	}
	else if (mRightMouseDown) {
		float DeltaX = (xpos - mCurrentX) * mSpeed;
		float DeltaY = (ypos - mCurrentY) * mSpeed;
		//如果鼠标向右，只需要相机位置向其右边移动就行，
		//如果鼠标向上，想要让图片也向上，则相机位置要向下。想不通不用太较真，反正加不行就减
		mCamera->mPosition += mCamera->mRight * DeltaX;
		mCamera->mPosition -= mCamera->mUp * DeltaY;
	}
	mCurrentX = xpos;
	mCurrentY = ypos;
}

void TrackBallController::onScroll(float offset)
{
	mCamera->scale(mScaleSpeed * offset);
}

void TrackBallController::pitch(float angle)
{
	//pitch是绕着相机的right方向旋转，也就是绕着自己的X轴方向旋转（同时也绕着原点旋转）。计算出变换矩阵
	auto mat = glm::rotate(glm::mat4(1.0), glm::radians(angle), mCamera->mRight);
	//用变换矩阵直接与相机的位置和有关向量相乘，即可得到旋转后的位置及有关向量
	mCamera->mUp = mat *glm::vec4( mCamera->mUp,0.0f);//将三维向量升级成4维时，最后一个是0表示转换为向量，
									//最后一个是1则表示转换为长度。计算结果是4维向量，赋值给三维向量会只给前三维
	mCamera->mPosition = mat * glm::vec4(mCamera->mPosition,1.0);
}

void TrackBallController::yaw(float angle)
{
	//yaw是绕着世界坐标系的y轴旋转。计算出变换矩阵
	auto mat = glm::rotate(glm::mat4(1.0), glm::radians(angle), glm::vec3(0.0,1.0,0.0));
	//用变换矩阵直接与相机的位置和有关向量相乘，即可得到旋转后的位置及有关向量
	mCamera->mUp = mat * glm::vec4(mCamera->mUp,0.0);
	mCamera->mRight = mat * glm::vec4(mCamera->mRight,0.0);
	mCamera->mPosition = mat * glm::vec4(mCamera->mPosition,1.0);

}
